import logging
from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler

logger = logging.getLogger(__name__)

class SimpleScheduler:
    def __init__(self):
        # 创建后台调度器
        self.scheduler = BackgroundScheduler()

    async def start(self):
        """启动调度器"""
        if not self.scheduler.running:
            self.scheduler.start()
            logger.info("调度器已启动")

    async def shutdown(self):
        """关闭调度器"""
        if self.scheduler.running:
            self.scheduler.shutdown()
            logger.info("调度器已关闭")

    def add_simple_job(self, func, seconds: int, job_id: str = None):
        """添加简单的时间间隔任务"""
        job = self.scheduler.add_job(
            func=func,
            trigger="interval",
            seconds=seconds,
            id=job_id or f"job_{int(datetime.now().timestamp() * 1000)}"
        )
        logger.info(f"已添加任务：{job.id}")
        return job

    def list_jobs(self):
        """列出所有的任务"""
        jobs = []
        for job in self.scheduler.get_jobs():
            jobs.append({
                "id": job.id,
                "name": job.name,
                "next_run_time": job.next_run_time,
                "trigger": str(job.trigger)
            })
        return jobs

    def remove_job(self, job_id: str):
        """移除任务"""
        try:
            self.scheduler.remove_job(job_id)
            logger.info(f"已移除任务：{job_id}")
            return True
        except Exception as e:
            logger.error(f"移除任务失败：{e}")
            return False

# 初始化调度器
scheduler = SimpleScheduler()
